package com.springsecurity.demo.controller;

import com.springsecurity.demo.vo.Student;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * @author : yj
 * @className : SecurityManagmentController
 * @creat : 2020-08-15 16:49
 * @desc : TODO
 */

@RestController
@RequestMapping("/management/api/")
public class SecurityManagementController {

    private static final List<Student> STUDENT = Arrays.asList(
            new Student(1, "Jack"),
            new Student(2, "Tom")
    );

    // TODO 直接在请求上使用注解方式实现不同权限下请求的限制, (@EnableGlobalMethodSecurity(prePostEnabled = true))
    // TODO hasRole(), hasAnyRole(), hasAuthorities(), hasAnyAuthorities()

    @GetMapping
    @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_ADMINTRAINEE')")
    public List<Student> getAllStudent() {
        return STUDENT;
    }

    /**
     * 新增
     * @param student
     */
    @PostMapping
    @PreAuthorize("hasAuthority('student:write')")
    public void registerStudent(@RequestBody Student student) {
        System.out.println("registerStudent: " + student);
    }

    /**
     * 修改
     * @param id
     * @param student
     */
    @PutMapping(path = {"{id}"})
    @PreAuthorize("hasAuthority('student:write')")
    public void modifyStudentById(@PathVariable("id") Integer id, @RequestBody Student student) {
        System.out.printf("%s - %s%n", id, student);
    }

    /**
     * 删除
     * @param id
     */
    @DeleteMapping(path = {"{id}"})
    @PreAuthorize("hasAuthority('student:write')")
    public void removeStudentById(@PathVariable("id") Integer id) {
        System.out.println(id);
    }
}
